package com.hzsparrow.ai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzsparrow.ai.entity.ChatHistory;
import com.hzsparrow.ai.entity.User;
import com.hzsparrow.ai.service.ChatHistoryService;
import com.hzsparrow.ai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天历史控制器
 */
@RestController
@RequestMapping("/api/chat-history")
public class ChatHistoryController {

    @Autowired
    private ChatHistoryService chatHistoryService;

    @Autowired
    private UserService userService;

    /**
     * 获取用户的所有聊天会话
     */
    @GetMapping("/sessions")
    public ResponseEntity<?> getUserSessions() {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            List<String> sessions = chatHistoryService.listUserSessions(user.getId());
            return ResponseEntity.ok(sessions);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 获取特定会话的聊天历史
     */
    @GetMapping("/session/{sessionId}")
    public ResponseEntity<?> getSessionHistory(
            @PathVariable String sessionId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "50") int size) {
        
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 验证此会话是否属于当前用户
            List<ChatHistory> checkHistory = chatHistoryService.lambdaQuery()
                    .eq(ChatHistory::getSessionId, sessionId)
                    .eq(ChatHistory::getUserId, user.getId())
                    .list();
            
            if (checkHistory.isEmpty() && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权访问此会话");
            }
            
            Page<ChatHistory> result = chatHistoryService.listSessionHistory(sessionId, page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("total", result.getTotal());
            response.put("pages", result.getPages());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("records", result.getRecords());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 获取用户的最近聊天记录
     */
    @GetMapping("/recent")
    public ResponseEntity<?> getRecentHistory(@RequestParam(defaultValue = "10") int limit) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            List<ChatHistory> history = chatHistoryService.listRecentHistory(user.getId(), limit);
            return ResponseEntity.ok(history);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 删除会话历史
     */
    @DeleteMapping("/session/{sessionId}")
    public ResponseEntity<?> deleteSessionHistory(@PathVariable String sessionId) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 验证此会话是否属于当前用户
            List<ChatHistory> checkHistory = chatHistoryService.lambdaQuery()
                    .eq(ChatHistory::getSessionId, sessionId)
                    .eq(ChatHistory::getUserId, user.getId())
                    .list();
            
            if (checkHistory.isEmpty() && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权删除此会话");
            }
            
            boolean result = chatHistoryService.deleteSessionHistory(sessionId);
            
            if (result) {
                return ResponseEntity.ok("会话历史删除成功");
            } else {
                return ResponseEntity.badRequest().body("会话历史删除失败");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 根据知识库ID获取聊天历史
     */
    @GetMapping("/knowledge-base/{knowledgeBaseId}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getChatHistoryByKnowledgeBase(
            @PathVariable Long knowledgeBaseId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Page<ChatHistory> result = chatHistoryService.listByKnowledgeBase(knowledgeBaseId, page, size);
            
            Map<String, Object> response = new HashMap<>();
            response.put("total", result.getTotal());
            response.put("pages", result.getPages());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("records", result.getRecords());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }
} 